package com.bham.teamwork.controller;
  
  
  import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.bham.teamwork.domain.User;
import com.bham.teamwork.service.IUserService;
import com.bham.teamwork.utils.ClientInfoUtil;
import com.bham.teamwork.utils.SecureTokenUtil;
import com.bham.teamwork.utils.encryptUtils.SHAUtil;
import java.util.Date;

/**
 * 
 * 
 * @author RuJia Li 
 * @author Federico Bacci
 * @author Alessandro Pozzer
 * 
 */

 @RequestMapping("/user")
 @Controller
 public class UserController {
	 
	 @Autowired
	 private IUserService iUserService;
	 
	 @RequestMapping(value ="/register.action",method =RequestMethod.GET)
     public ModelAndView register(HttpServletRequest request,HttpServletResponse response){
         ModelAndView mv = new ModelAndView("/register/register","command","success");
         return mv;
     }
	 
	 /**
	  * use to get user
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	 
	 @RequestMapping(value ="/addUserInfo.action",method =RequestMethod.POST)
     public void addUserInfo(HttpServletRequest request,HttpServletResponse response,String id) throws Exception{
         String username = request.getParameter("username");
         String fullname = request.getParameter("fullname");
         String password = request.getParameter("password");
         String email = request.getParameter("email");
         String validateCode = request.getParameter("validateCode");
         
         String check = (String)request.getSession().getAttribute("checkcode");
         List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
         Map map = new HashMap<String, Object>();
         
         if(validateCode!=null&&validateCode.equalsIgnoreCase(check)){
        	 password = SHAUtil.SHA256(password);
             User user = new User();
             user.setFullname(fullname);
             user.setPassword(password);
             user.setUsername(username);
             user.setEmail(email);
             iUserService.saveUser(user);
             map.put("flag", "success");
         }else{
        	 map.put("flag", "fail");
         }
         
         datas.add(map);
         String jsonResult = JSON.toJSONString(datas);
         renderData(response,jsonResult);
     }
	 
	 @RequestMapping("/login.action")
     public ModelAndView login(HttpServletRequest request,HttpServletResponse response){
         ModelAndView mv = new ModelAndView("/login/login","command","LOGIN SUCCESS, ");
         return mv;
     }
	 
	 @RequestMapping("/index.action")
     public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
         ModelAndView mv = new ModelAndView("/index/index");
         return mv;
     }
	 
	 @RequestMapping(value ="/resetpwd.action",method =RequestMethod.GET)
     public ModelAndView resetpwd(HttpServletRequest request,HttpServletResponse response){
         ModelAndView mv = new ModelAndView("/resetpwd/resetpwd","command","success");
         return mv;
     }
	 
	 
	 /**
	  * use to get user
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	 
	 @RequestMapping(value ="/changepwd.action",method =RequestMethod.POST)
     public void changepwd(HttpServletRequest request,HttpServletResponse response,String id) throws Exception{
         String oldPassword = request.getParameter("oldPassword");
         String newPassword = request.getParameter("newPassword");
         
         String username = request.getSession().getAttribute("SESSIONUSER")+"";
         
         User user = iUserService.getUser(username);
         
         List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
         Map map = new HashMap<String, Object>();
         
         if(user!=null){
        	 String passworddb = user.getPassword();
        	 if(passworddb!=null&&passworddb.equals(oldPassword)){
        		 user.setPassword(newPassword);
        		 iUserService.saveUser(user);
        		map.put("flag", "success");
        	 }else{
        		 map.put("flag", "fail");
        	 }
         }else{
        	 map.put("flag", "fail");
         }
         datas.add(map);
         String jsonResult = JSON.toJSONString(datas);
         renderData(response,jsonResult);
     }
	 
	 
	 
	 
	 
	 /**
	  * use to get userMap
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value ="/verifyUser.action",method =RequestMethod.POST)
     public void verifyUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	 String username = request.getParameter("username");
         String password = request.getParameter("password");
         String validateCode = request.getParameter("validateCode");
         
         String check = (String)request.getSession().getAttribute("checkcode");
         List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
         Map map = new HashMap<String, Object>();
         
         
         if(validateCode!=null&&validateCode.equalsIgnoreCase(check)){
        	 User user = iUserService.getUser(username);
             
             if(user!=null){
            	 String passworddb = user.getPassword();
            	 if(passworddb!=null&&passworddb.equals(password)){
            		map.put("flag", "success");
            		
            		Date date = new Date(); //当前时间
            		String  clientIp  = ClientInfoUtil.getClientIpAddr(request);  //IP地址
         			String  ltapToken = SecureTokenUtil.creatLtapToken(username,clientIp,date,"120"); //获取加密后的数据
         			map.put("ltapToken", ltapToken);
         			request.getSession().setAttribute("SESSIONUSER",username);
            	 }else{
            		 map.put("flag", "fail");
            	 }
             }else{
            	 map.put("flag", "fail");
             }
         }else{
        	 map.put("flag", "fail");
         }
         
         datas.add(map);
         String jsonResult = JSON.toJSONString(datas);
         renderData(response,jsonResult);
     }
	 
     
     
     private void renderData(HttpServletResponse response, String data) {
    	    PrintWriter printWriter = null;
    	    try {
    	      printWriter = response.getWriter();
    	      printWriter.print(data);
    	    } catch (IOException ex) {
    	    	
    	    } finally {
    	      if (null != printWriter) {
    	        printWriter.flush();
    	        printWriter.close();
    	      }
    	    }
     }
     
     
 }